package com.yincheng.oes.business.exam.export;

import com.yincheng.oes.business.exam.base.entity.Paper;
import com.yincheng.oes.business.exam.createpaper.service.PaperService;
import com.yincheng.oes.business.exam.export.model.ExportPaperParam;
import com.yincheng.oes.business.exam.judgepaper.entity.PaperStudentResult;
import com.yincheng.oes.business.exam.judgepaper.service.PaperResultService;
import com.yincheng.oes.business.model.result.BusinessResult;
import freemarker.template.TemplateException;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yangsy
 * @version 1.0.0
 * @since
 * 创建时间：2018年7月28日
 * <p>
 * 功能描述：试卷导出controller层
 * <p>
 * 邮箱地址：446948434@qq.com
 */
@Controller
@RequestMapping("/export")
public class ExportController {
    /**
     * logger 日志
     */
    private static final Logger logger = LogManager.getLogger(ExportController.class);
    @Autowired
    private PaperResultService paperResultService;

    @Autowired
    private ExportService exportService;

    @Autowired
    private PaperService paperService;

    @RequestMapping(value = "/studentAnswer.json", method = RequestMethod.GET)
    public void studentAnswer(String resultId, HttpServletResponse response) throws IOException, TemplateException {

        PaperStudentResult paperResult = paperResultService.getPaperResult(resultId);
        String fileName = paperResult.getPaperName() + "-" + paperResult.getUserName() + ".doc";
        String newName = encodeFileName(fileName);
        response.reset();
        response.setContentType(getContextType(fileName));
        response.setHeader("Content-disposition", "attachment; filename=" + newName);
        // response.setHeader("Content-Length", String.valueOf(attachment.getFileSize()));
        paperResultService.exportStudentAnswerWord(resultId, response.getOutputStream());
    }

    @RequestMapping(value = "/word/exportPaperStatistics.json", method = RequestMethod.GET)
    public void exportPaperStatistics(String paperId, HttpServletResponse response)
            throws IOException, TemplateException {
        Paper paper = paperService.getPaper(paperId);
        String fileName = paper.getPaperName() + ".doc";
        String newName = URLEncoder.encode(fileName, "UTF-8");
        response.reset();
        response.setContentType(getContextType(fileName));
        response.setHeader("Content-disposition", "attachment; filename=" + newName);
        exportService.exportPaperStatisticsByWord(paperId, response.getOutputStream());
    }

    private static String getContextType(String filename) {
        String extension = FilenameUtils.getExtension(filename).toLowerCase();
        String context = contextMap.get(extension);

        if (context != null) {
            return context + "; charset=utf-8";
        } else {
            return "application/octet-stream; charset=utf-8";
        }
    }

    private static final Map<String, String> contextMap = new HashMap<>();

    static {
        contextMap.put("xls", "application/-excel");
        contextMap.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        contextMap.put("doc", "application/vnd.msword");
        contextMap.put("docx", "application/octet-stream");
        contextMap.put("ppt", "applications/-powerpoint");
    }

    /**
     * 批量导出学生成绩
     * @param param 导出试卷入参
     * @return 导出结果
     */
    @RequestMapping(value = "/batchDownloadStudentAnswers.json", method = RequestMethod.POST)
    @ResponseBody
    public BusinessResult batchDownloadStudentAnswers(@RequestBody ExportPaperParam param) {
        logger.debug("start batchDownloadStudentAnswers, param is {}", param);
        return paperResultService.exportZipStudentAnswers(param);
    }

    /**
     * 导出试卷
     *
     * @param param ExportPaperParam
     * @param response response
     * @throws IOException IOException
     * @throws TemplateException TemplateException
     */
    @RequestMapping(value = "/exportWordUndo.json", method = RequestMethod.GET)
    public void exportWordUndo(ExportPaperParam param, HttpServletResponse response) throws IOException, TemplateException {
        logger.debug("start exportWordUndo, param is {}", param);
        dealResponse(param.getPaperId(), response);
        paperService.exportUndoPaper(param, response.getOutputStream());
    }

    @RequestMapping(value = "/exportWordWithAnswer.json", method = RequestMethod.GET)
    public void exportWordWithAnswer(String paperId, HttpServletResponse response)
            throws IOException, TemplateException {
        logger.debug("start exportWordWithAnswer, paperId is {}", paperId);
        dealResponse(paperId, response);
        paperService.exportPaperWithAnswer(paperId, response.getOutputStream());
    }

    /**
     * 导出试卷测评分析报告
     *
     * @param paperId 试卷id
     * @param response HttpServletResponse
     * @throws IOException IOException
     * @throws TemplateException TemplateException
     */
    @Deprecated
    @RequestMapping(value = "/exportAnalysisPaper.json", method = RequestMethod.GET)
    public void exportAnalysisPaper(String paperId, HttpServletResponse response)
            throws IOException, TemplateException {

        dealResponse(paperId, response);
        paperService.exportPaperWithAnswer(paperId, response.getOutputStream());
    }

    private String encodeFileName(String fileName) throws UnsupportedEncodingException {
        return URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20").replaceAll("%28", "\\(")
                .replaceAll("%29", "\\)").replaceAll("%3B", ";").replaceAll("%40", "@").replaceAll("%23", "\\#")
                .replaceAll("%26", "\\&").replaceAll("%2C", "\\,");
    }

    private void dealResponse(String paperId, HttpServletResponse response) throws UnsupportedEncodingException {
        Paper paper = paperService.getPaper(paperId);
        String fileName = paper.getPaperName() + ".doc";
        String newName = encodeFileName(fileName);
        response.reset();
        response.setContentType(getContextType(fileName));
        response.setHeader("Content-disposition", "attachment; filename=" + newName);
    }

}
